<template>
  <header class="header-bar">
    <div class="logo-area">
      <span class="site-name">医疗设备管理系统</span>
    </div>

    <!-- 动态导航标签 -->
    <nav class="main-tabs">
      <button 
        v-for="tab in filteredTabs" 
        :key="tab.value"
        :class="{ active: currentMainTab === tab.value }"
        @click="$emit('mainTabChanged', tab.value)"
      >
        {{ tab.label }}
      </button>
    </nav>

    <div class="user-area">
      <!-- 显示当前用户信息 -->
      <el-dropdown>
        <span class="user-info">
          <el-avatar size="small" :src="defaultAvatar" />
          <span class="user-name">{{ userName }}</span>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 动态角色选择下拉框 -->
      <el-select
  :model-value="selectedRole"
  @update:model-value="onRoleSelect"
  placeholder="选择角色"
  size="small"
  style="width: 140px;"
  :loading="isLoading"
>
  <el-option
    v-for="role in roleOptions"
    :key="role.value"
    :label="role.label"
    :value="role.value"
  />
</el-select>

    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { storeToRefs } from 'pinia'
import { useTokenStore } from '@/stores/token'

interface Permission {
  value: string
  label: string
}

interface Role {
  id: number
  roleName: string
  permissions: Permission[]
}

// store
const userStore = useTokenStore()
const {userName, id } = storeToRefs(userStore)

// 默认头像
const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 状态定义
const roleList = ref<Role[]>([])
const selectedRole = ref<number | null>(null)
const isLoading = ref(false)

// 当前主标签页的值来自父组件
const props = defineProps({
  currentMainTab: {
    type: String,
    required: true
  }
})
console.log(props)
// 定义emit事件
const emit = defineEmits(['mainTabChanged'])

// 获取后端角色 + 权限信息
const fetchRolesAndPermissions = async () => {
  isLoading.value = true
  try {
    const userId = id.value || 1
    console.log("登录用户:", userId, userName.value)
    const res = await request.get('/role/getRolesAndPermission', {
      params: { userId }
    })
    if (res.status === 0 && Array.isArray(res.data)) {
      roleList.value = res.data
      // 默认选中第一个角色
      selectedRole.value = res.data[0]?.id || null
      userStore.selectedRole=res.data[0]?.id || null
      // 自动选择第一个标签页
      autoSelectFirstTab()
    } else {
      ElMessage.error('获取角色权限失败')
    }
  } catch (err) {
    console.error('获取角色权限失败:', err)
    ElMessage.error('获取角色权限失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 自动选择第一个标签页
const autoSelectFirstTab = () => {
  const currentRole = roleList.value.find(r => r.id === selectedRole.value)
  if (currentRole && currentRole.permissions.length > 0) {
    const firstTab = currentRole.permissions[0].value
    emit('mainTabChanged', firstTab)
  }
}

// 生命周期加载
onMounted(() => {
  fetchRolesAndPermissions()
})

// 角色下拉选项
const roleOptions = computed(() =>
  roleList.value.map(role => ({
    label: role.roleName,
    value: role.id
  }))
)

// 中间按钮 tabs 映射自权限
const filteredTabs = computed(() => {
  const currentRole = roleList.value.find(r => r.id === selectedRole.value)
  if (!currentRole) return []
  return currentRole.permissions.map(p => ({
    value: p.value,
    label: p.label
  }))
})

// 角色变更
// const handleRoleChange = async (newRole: number) => {
//   try {
//     await ElMessageBox.confirm('确定要切换角色吗?', '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning'
//     })
//     selectedRole.value = newRole
//     // 切换角色后自动选择第一个标签页
//     autoSelectFirstTab()
//   } catch {
//     // 用户取消操作，恢复原值
//     //selectedRole.value = roleList.value.find(r => r.id === selectedRole.value)?.id || null
//   }
// }
const onRoleSelect = async (newRole: number) => {
  try {
    await ElMessageBox.confirm('确定要切换角色吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    selectedRole.value = newRole
    userStore.selectedRole=newRole
    autoSelectFirstTab()
  } catch {
    // 用户取消，不修改 selectedRole
  }
}

// 登出
const logout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    userStore.logout()
    window.location.href = '/login.html'
  } catch {
    // 用户取消操作
  }
}
</script>

<style scoped>
.header-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: var(--header-bg, #42b983);
  color: var(--text-color, white);
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.logo-area {
  flex: 0 0 200px;
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.site-name {
  font-family: 'Arial', sans-serif;
  letter-spacing: 1px;
}

.main-tabs {
  flex: 1;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.main-tabs button {
  background: none;
  border: none;
  color: var(--text-color, white);
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  font-weight: 500;
}

.main-tabs button::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: var(--primary-color, #42b983);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.main-tabs button:hover {
  background: rgba(255, 255, 255, 0.1);
}

.main-tabs button:hover::after,
.main-tabs button.active::after {
  transform: scaleX(1);
  background:pink;
}

.main-tabs button.active {
  color: white;
  font-weight: bold;
}

.user-area {
  flex: 0 0 300px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background 0.3s;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.1);
}

.user-name {
  font-size: 14px;
}

@media (max-width: 768px) {
  .header-bar {
    padding: 0 10px;
    height: 50px;
  }
  
  .logo-area {
    flex: 0 0 120px;
    font-size: 16px;
  }
  
  .user-area {
    flex: 0 0 200px;
  }
  
  .main-tabs {
    gap: 8px;
  }
  
  .main-tabs button {
    padding: 6px 10px;
    font-size: 12px;
  }
}

:deep(.el-select .el-input__inner) {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
  color: white;
}

:deep(.el-select .el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.7);
}

:deep(.el-select .el-input__suffix) {
  color: white;
}
</style>